package com.example.llh.zyfypt_110llh.model.article;

import com.example.llh.zyfypt_110llh.bean.article.ArticleBean;
import com.example.llh.zyfypt_110llh.iface.article.ArticleListener;
import com.example.llh.zyfypt_110llh.iface.article.Articleiface;
import com.example.llh.zyfypt_110llh.service.article.ArticleService;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//model获取文章数据
public class ArticleModel implements Articleiface {
    private Retrofit retrofit;
    private String BASEURL="http://amicool.neusoft.edu.cn/";//网址前半部分
    //构造函数
    public ArticleModel(){
        //   retrofit第一步，生成retrofit对象
        retrofit=new Retrofit.Builder()
                .baseUrl(BASEURL)//给定网址
                .addConverterFactory(GsonConverterFactory.create())//指定转换方式
                .build();//build出来
    }
    //获取文章数据
    @Override
    //           实现回调，articleListener将他回调到fragment当中。getResultList实际是Articleiface中未实现的方法
    public void getResultList(String mod, int page, String sessionID, final ArticleListener articleListener) {
        ArticleService articleService=retrofit.create(ArticleService.class);

        Call<List<ArticleBean>> call
                =articleService.getResult(mod,page,sessionID);
        call.enqueue(new Callback<List<ArticleBean>>() {
            @Override
            public void onResponse(Call<List<ArticleBean>> call, Response<List<ArticleBean>> response) {
                if(response.isSuccessful()&&response!=null){
                    articleListener.onResponse(response.body());
                }
                else
                    articleListener.onFail("onresponse fail");
            }
            @Override
            public void onFailure(Call<List<ArticleBean>> call, Throwable t) {
                articleListener.onFail(t.toString());
            }
        });
    }
}
